package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrdersService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: zhaoss
 * @Date: 2023/5/6 - 05 - 06 - 17:21
 * @Description: com.sky.service.impl
 * @version: 1.0
 */
@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrdersDetailMapper ordersDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;


    /**
     * 下单
     *
     * @param dto
     * @return
     */
    @Override
    public Result submit(OrdersSubmitDTO dto) {
        //判断地址是否为空
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        if (addressBook == null) {
            return Result.error(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //判断购物车是否为空
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.getByUserId(BaseContext.getCurrentId());
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            return Result.error(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //新增订单表
        Orders order = new Orders();
        BeanUtils.copyProperties(dto, order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(BaseContext.getCurrentId());
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());
        ordersMapper.addOrders(order);
        //新增订单明细表
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetailList.add(orderDetail);
        }
        ordersDetailMapper.addOrdersDetailList(orderDetailList);
        //清空购物车
        shoppingCartMapper.deleteCar(BaseContext.getCurrentId());
        //返回数据
        OrderSubmitVO vo = OrderSubmitVO.builder()
                .id(order.getId())
                .orderAmount(order.getAmount())
                .orderNumber(order.getNumber())
                .orderTime(order.getOrderTime())
                .build();
        return Result.success(vo);
    }

    /**
     * 查询历史订单
     *
     * @param dto
     * @return
     */
    @Override
    public Result pageHistoryOrders(OrdersPageQueryDTO dto) {
        if (dto.getPage() == null) {
            dto.setPage(0);
        }
        if (dto.getPageSize() == null) {
            dto.setPageSize(5);
        }
        //分页
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        //调用dao

        /*dto.setBeginTime(LocalDateTime.of(1900,01,01,00,00,00));
        dto.setBeginTime(LocalDateTime.of(2900,01,01,00,00,00));*/
        dto.setUserId(BaseContext.getCurrentId());

        Page<OrderVO> page = ordersMapper.pageOrders(dto);
        long total = page.getTotal();
        List<OrderVO> orderVOList = page.getResult();
        for (OrderVO orderVO : orderVOList) {
            List<OrderDetail> orderDetailList = ordersDetailMapper.getByOrderId(orderVO.getId());
            orderVO.setOrderDetailList(orderDetailList);
        }


        PageResult pageResult = new PageResult(total, orderVOList);
        return Result.success(pageResult);
    }

    /**
     * 订单详情
     *
     * @param id
     * @return
     */
    @Override
    public Result getDetails(Long id) {
        if (id == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        OrderVO orderVO = ordersMapper.getById(id);
        List<OrderDetail> orderDetailList = ordersDetailMapper.getByOrderId(id);
        orderVO.setOrderDetailList(orderDetailList);


        return Result.success(orderVO);
    }

    /**
     * 取消订单
     *
     * @param id
     * @return
     */
    @Override
    public Result putOrder(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.CANCELLED);
        ordersMapper.putOrder(orders);
        return Result.success();
    }

    /**
     * 再来一单
     *
     * @param id
     * @return
     */
    @Override
    public Result recurOrder(Long id) {
        if (id == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }

        List<OrderDetail> orderDetailList = ordersDetailMapper.getByOrderId(id);
        ShoppingCart shoppingCart = new ShoppingCart();
        for (OrderDetail orderDetail : orderDetailList) {
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.add(shoppingCart);
        }

        return Result.success();
    }

    /**
     * 查询管理端订单
     *
     * @param dto
     * @return
     */
    @Override
    public Result pageOrders(OrdersPageQueryDTO dto) {
        if (dto.getPage() == null) {
            dto.setPage(0);
        }
        if (dto.getPageSize() == null) {
            dto.setPageSize(5);
        }
        //分页
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        //调用dao

        Page<OrderVO> page = ordersMapper.pageOrders(dto);
        long total = page.getTotal();
        List<OrderVO> orderVOList = page.getResult();

        for (OrderVO orderVO : orderVOList) {
            List<OrderDetail> orderDetailList = ordersDetailMapper.getByOrderId(orderVO.getId());
            orderVO.setOrderDetailList(orderDetailList);

            String str = "";
            for (OrderDetail orderDetail : orderDetailList) {
                String name = orderDetail.getName();
                Integer number = orderDetail.getNumber();
                str += (name+"x"+number+"\r\n");
            }
            orderVO.setOrderDishes(str);
        }


        PageResult pageResult = new PageResult(total, orderVOList);
        return Result.success(pageResult);
    }

    /**
     * 查询各个订单状态数量
     *
     * @return
     */
    @Override
    public Result getStatistics() {

        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = ordersMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = ordersMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = ordersMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);


        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return Result.success(orderStatisticsVO);

    }

    /**
     * 接单
     * @param dto
     * @return
     */
    @Override
    public Result confirm(OrdersConfirmDTO dto) {
        OrderVO vo = ordersMapper.getById(dto.getId());
        vo.setStatus(Orders.CONFIRMED);
        Orders orders=new Orders();
        BeanUtils.copyProperties(vo,orders);
        ordersMapper.putOrder(orders);
        return Result.success();
    }

    /**
     * 拒单
     *
     * @param dto
     * @return
     */
    @Override
    public Result rejection(OrdersRejectionDTO dto) {
        OrderVO vo = ordersMapper.getById(dto.getId());
        vo.setStatus(Orders.CANCELLED);
        vo.setRejectionReason(dto.getRejectionReason());
        Orders orders=new Orders();
        BeanUtils.copyProperties(vo,orders);
        ordersMapper.putOrder(orders);
        return Result.success();
    }

    /**
     * 取消定单
     *
     * @param dto
     * @return
     */
    @Override
    public Result cancel(OrdersCancelDTO dto) {
        OrderVO vo = ordersMapper.getById(dto.getId());
        vo.setStatus(Orders.CANCELLED);
        vo.setRejectionReason(dto.getCancelReason());

        Orders orders=new Orders();
        BeanUtils.copyProperties(vo,orders);

        ordersMapper.putOrder(orders);

        return Result.success();

    }

    /**
     * 派送定单
     *
     * @param id
     * @return
     */
    @Override
    public Result delivery(Long id) {
        OrderVO vo = ordersMapper.getById(id);
        vo.setStatus(Orders.DELIVERY_IN_PROGRESS);

        Orders orders=new Orders();
        BeanUtils.copyProperties(vo,orders);

        ordersMapper.putOrder(orders);

        return Result.success();
    }

    /**
     * 完成定单
     *
     * @param id
     * @return
     */
    @Override
    public Result complete(Long id) {
        OrderVO vo = ordersMapper.getById(id);
        vo.setStatus(Orders.COMPLETED);

        Orders orders=new Orders();
        BeanUtils.copyProperties(vo,orders);

        ordersMapper.putOrder(orders);

        return Result.success();
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        ordersMapper.update(orders);

        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

    }
    /**
     * 用户催单
     *
     * @param id
     */
    public void reminder(Long id) {
        // 查询订单是否存在
        Orders orders = ordersMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.UNKNOWN_ERROR);
        }

        //基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type", 2);//2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
